# -*-coding:utf-8 -*-
import hashlib
from datetime import datetime
import time
import requests

from third_api import config


class KYApi:

    def __init__(self, *args, **kwargs):
        self.baseurl = "http://androidsdk.adasplus.com"

    def get_access_token(self):
        res = requests.post(f"{self.baseurl}/reportform_login", data={
            "un": config.KY['UW'],
            "pw": config.KY['PW'],
        }).json()

        return res['token']

    def get_vehicles(self):
        '''
        获取车辆列表
        :return:
        '''
        page = 1
        vehicle_infos = {}
        while True:
            res = requests.post(f'{self.baseurl}/reportform_mongodb_get_carlist_info', data={
                "child_merchant_id": config.KY['CHILD_MERCHANT_ID'],
                "page": page,
                "item_total": 0,
                "car_state": 0,
                "bar_flag": 1,
                "ids": "",
                "data": [{"car_id": "", "filter_flag": 1, "child_merchant_id": config.KY['CHILD_MERCHANT_ID']}],
                "dtoken": self.get_access_token()
            }).json()

            for infos in res['data']:
                vehicle_infos[infos['imei']] = infos
            if res['item_total'] >= len(vehicle_infos):  # 没有下一页
                break
            page += 1
        return vehicle_infos

    def media_info(self, endpoint: str, media_url: str):
        '''图片转换'''
        res = requests.post(f'{self.baseurl}/reportform_mongodb_get_imgurl', data={
            "url": endpoint + media_url,
            "dtoken": self.get_access_token()
        }).json()

        return res['url']

    def live(self, stream_id, imei, channel_id, flag):
        """创建直播"""

        data = {
            "imei": imei,
            "type": channel_id,
            "time": int(time.time()),
            "merchantid": config.KY['CHILD_MERCHANT_ID'],
            "rtmp": f'{config.RTMP_URL}{stream_id}_{channel_id}',
            "flag": flag
        }
        data['accesskey'] = self.get_accesskey(data)
        res = requests.post(url=f'{self.baseurl}/remoteLive_create', data=data).json()
        print(res)
        data_dict = {"resp_code": 1, "message": data['rtmp']}
        return data_dict

    def get_accesskey(self, data):
        """获得访问秘钥"""

        # 根据键值从小到大排序
        sort_data = sorted(data.items(), key=lambda item: item[0])

        # value -> str
        sort_data = [str(d[1]) for d in sort_data]

        # 拼接 value 和 秘钥
        key = "%s|%s" % ("".join(sort_data), config.SECRETKEY)

        # md5 处理
        return hashlib.md5(bytes(key, encoding="utf-8")).hexdigest()

if __name__ == '__main__':
    a = KYApi()
    print(a.get_vehicles())
    print(a.live(128,"866275036358332",0,0))
